package com.firebird.app.fekpsl.ui.fragment

import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.util.Base64
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.firebird.app.fekpsl.R
import com.firebird.app.fekpsl.constant.Constant
import com.firebird.app.fekpsl.ext.showToast
import com.firebird.app.fekpsl.ui.activity.user.LoginActivity
import com.firebird.app.fekpsl.ui.activity.me.MemberLevelActivity
import com.firebird.app.fekpsl.ui.activity.me.PersonInfoActivity
import com.firebird.app.fekpsl.ui.activity.me.SettingActivity
import com.firebird.app.fekpsl.ui.activity.me.StatsticalInfoActivity
import com.firebird.app.fekpsl.utils.MemberUtil.getLevelName
import com.firebird.app.fekpsl.utils.Preference
import kotlinx.android.synthetic.main.fragment_me.*
import kotlinx.android.synthetic.main.fragment_me.iv_avatar
import java.math.RoundingMode
import java.text.DecimalFormat

/**
 * A simple [Fragment] subclass.
 *
 */
class MeFragment : Fragment() {

    companion object {
        fun getInstance(): MeFragment = MeFragment()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_me, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        refreshData()
        initListener()
    }

    override fun onResume() {
        super.onResume()
        //showToast("刷新数据1")
        refreshData()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (MeFragment != null && !hidden) {
            // showToast("刷新数据2")
            refreshData()
        }
    }

    private fun refreshData(){
        val pf_niceName:String by Preference(Constant.NICE_NAME_KEY, "")
        val pf_realName:String by Preference(Constant.REAL_NAME_KEY, "")
        val pf_userId:String by Preference(Constant.USER_ID_KEY, "")
        val pf_isExplicit:Int by Preference(Constant.IS_EXPLICIT_KEY, 1)
        val pf_area:String by Preference(Constant.AREA_KEY, "")
        val pf_creditScore:Int by Preference(Constant.CREDIT_SCORE_KEY, 100)
        val pf_copperCash:Long by Preference(Constant.COPPER_CASH_KEY, 0)
        val pf_goldIngot:Long by Preference(Constant.GOLD_INGOT_KEY, 0)
        val pf_levelScore:Long by Preference(Constant.LEVEL_SCORE_KEY,0)
        val pf_avatar_base64:String by Preference(Constant.AVATAR_KEY,"")
        if(pf_isExplicit==1){
            val tmp_str="["+getLevelName(pf_levelScore)+"]"+pf_niceName
            mUserName.setText(tmp_str)
        }else{
            val tmp_str="["+getLevelName(pf_levelScore)+"]"+pf_realName
            mUserName.setText(tmp_str)
        }
        mUserID.setText("ID:FK$pf_userId")
        if (pf_area.length>0){
            if (pf_area.length>8){
                mArea.setText("$pf_area")
            }else {
                mArea.setText("地区:$pf_area")
            }
        }else{
            mArea.setText("地区:--")
        }
        val end_pos=4+pf_creditScore.toString().length
        var style: SpannableStringBuilder = SpannableStringBuilder("信用分:$pf_creditScore")
        style.setSpan( ForegroundColorSpan(Color.WHITE), 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        style.setSpan( ForegroundColorSpan(Color.GREEN), 4, end_pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        mCreditScore.setText(style)
        var tmp_str:String=""
        if (pf_copperCash>10000) {
            tmp_str=getNoMoreThanTwoDigits( pf_copperCash/ 10000.0)+"万"
        }else{
            tmp_str=pf_copperCash.toString()
        }
        mCopperCash.setText(tmp_str)
        if (pf_goldIngot>10000) {
            tmp_str=getNoMoreThanTwoDigits( pf_goldIngot/ 10000.0)+"万"
        }else{
            tmp_str=pf_goldIngot.toString()
        }
        mGoldIngot.setText(tmp_str)
        val decodedString = Base64.decode(pf_avatar_base64!!.split(",".toRegex()).toTypedArray()[1], Base64.DEFAULT)
        val decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size)
        iv_avatar.setImageBitmap(decodedByte)
    }

    private fun initListener() {
        mUserName.setOnClickListener {
            Intent(activity, PersonInfoActivity::class.java).run {
                startActivity(this)
            }
        }
        mUserID.setOnClickListener {
            Intent(activity, PersonInfoActivity::class.java).run {
                startActivity(this)
            }
        }
        mArea.setOnClickListener {
            Intent(activity, PersonInfoActivity::class.java).run {
                startActivity(this)
            }
        }
        mCreditScore.setOnClickListener {
            Intent(activity, PersonInfoActivity::class.java).run {
                startActivity(this)
            }
        }
        mLogin.setOnClickListener {
            Intent(activity, LoginActivity::class.java).run {
                startActivity(this)
            }
        }
        mMemberLevel.setOnClickListener {
            Intent(activity, MemberLevelActivity::class.java).run {
                startActivity(this)
            }
        }
        mStatisticalInfo.setOnClickListener {
            Intent(activity, StatsticalInfoActivity::class.java).run {
                startActivity(this)
            }
        }
        mCollection.setOnClickListener {
            showToast(getString(R.string.established_tip))
        }
        mSetting.setOnClickListener {
            Intent(activity, SettingActivity::class.java).run {
                startActivity(this)
            }
        }
        mHelpFeedback.setOnClickListener {
            showToast(getString(R.string.established_tip))
        }
        mRecommendToFriend.setOnClickListener {
            showToast(getString(R.string.established_tip))
        }
        mUploadLog.setOnClickListener {
            showToast(getString(R.string.established_tip))
        }

    }

    /**
     * OnClickListener  method 2
     */
    /*
    private val onClickListener = View.OnClickListener { view ->
        when (view.id) {
            R.id.mUserName , R.id.mUserID,R.id.mArea,R.id.mCreditScore-> {
                Intent(activity, PersonInfoActivity::class.java).apply {
                    startActivity(this)
                }
            }
        }
    }
    */

    /**
     * 对入参保留最多两位小数(舍弃末尾的0)，如:
     * 3.345->3.34
     * 3.40->3.4
     * 3.0->3
     */
    fun getNoMoreThanTwoDigits(number: Double): String {
        val format = DecimalFormat("0.##")
        //未保留小数的舍弃规则，RoundingMode.FLOOR表示直接舍弃。
        format.roundingMode = RoundingMode.FLOOR
        return format.format(number)
    }

}
